#pragma once

#include "Reactor.hpp"
#include "Connection.hpp"
#include "Log.hpp"
#include "Handler.hpp"
#include "Socket.hpp"


class Accepter
{
public:
    static void Accept(Connection *conn)
    {
        // errno = 0;
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int fd = conn->Sockfd();
        // ET模式要求一次把数据读完，循环获取连接
        while(true)
        {
            int newsock = accept(fd, (struct sockaddr*)&peer, &len);
            if(newsock > 0)
            {
                // 设置fd为非阻塞
                SetNonBlock(newsock);
                ILOG("获取连接成功, ip: %s, port: %d", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));
                Connection *newconn = ConntionFactory::BuildNormalConnection(newsock, conn->_R, 
                                                    Handler::Recver, Handler::Sender, Handler::Excepter);
                conn->_R->AddConnection(newconn);
            }
            else
            {
                if(errno == EAGAIN) break;
                else if(errno == EINTR) continue;
                else
                {
                    ELOG("accept error ...");
                }
            }
        }
    }

};